###
# Copyright (c) 2008, Scott Saad
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

###

from P4 import P4
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks


class Perforce(callbacks.PluginRegexp):
    """Query a Perforce server"""

    threaded = False
    unaddressedRegexps = ['snarfChangelist']

    def __init__(self, irc):
        self.__parent = super(Perforce, self)
        self.__parent.__init__(irc)
        self.p4 = P4()

    def _getChanges(self, changes):

        #init perforce
        self.p4.port = self.registryValue('port')
        self.p4.client = self.registryValue('client')
        self.p4.user = self.registryValue('user')
        self.p4.password = self.registryValue('password')
        self.p4.connect()
        self.p4.run_login()

        change_strings = []
        for change_num in changes:
            # Query the changelist
            change = self.p4.run_changes('-l', format('@%s,@%s', change_num,
                change_num))

            # Format 
            if ( len(change) > 0 ):
                p4user = str(change[0]['user']).rstrip()
                p4changelist = str(change[0]['change']).rstrip()
                p4desc = str(change[0]['desc']).rstrip()
                msg = format('perforce change %q submitted by %s => %s', p4changelist, 
                        p4user, p4desc)
            else:
                msg = format('perforce change %q not found', number)

            change_strings.append(msg)

        self.p4.disconnect()
        return change_strings

    def changelist(self, irc, msg, args, number):
        """<number>
    
        query a changelist <number> from perforce
        """
        irc.reply(self._getChanges([number])[0])
    changelist = wrap(changelist, ['int'])

    def snarfChangelist(self, irc, msg, match):
        r"""(?P<type>change|changelist)\b[\s#]*(?P<num>\d+)"""
        channel = msg.args[0]
        change_nums = match.group('num').split()
        self.log.debug('Snarfed changelist numbers: ' + ' '.join(change_nums))
        change_strings = self._getChanges(change_nums)
        for change in change_strings:
            irc.reply(change, prefixNick=False)
                
Class = Perforce

# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
